﻿using System;
using System.Linq;
using System.Web.UI.WebControls;

namespace ECommerce.Controls
{
	public partial class OrderSummary : BaseUserControl
	{
		private Service.IShoppingCartItemService _ShoppingCartItemService;
		private Service.IProductService _ProductService;

		protected void Page_Load(object sender, EventArgs e)
		{
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			HyperLinkAlterCart.Text = GetLocalResourceString("OrderSummary.AlterCartLink.Text");
			HyperLinkAlterCart.NavigateUrl = "~/ShoppingCart.aspx";
			this.LOrderProductListTitle.Text = GetLocalResourceString("OrderSummary.OrderProductListTitle");
			this.LPriceSummaryLabel.Text = GetLocalResourceString("ShoppingCart.PriceSummaryLable");

			BindCartitems();
		}

		protected void GridOrderProduct_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.Header)
			{
				e.Row.Cells[0].Text = GetLocalResourceString("ShoppingCart.ProdNameCellHeaderText");
				e.Row.Cells[1].Text = GetLocalResourceString("ShoppingCart.QuantityCellHeaderText");
				e.Row.Cells[2].Text = GetLocalResourceString("ShoppingCart.ListPriceCellHeaderText");
			}
		}

		private void BindCartitems()
		{
			if (SiteContext.Current == null || SiteContext.Current.WorkingLanguage == null)
			{
				Server.Transfer("~/HomePage.aspx");
			}

			var user = SiteContext.Current.User;

			if (user == null)
			{
				Server.Transfer("~/Login.aspx");
			}
			else
			{
				if(_ShoppingCartItemService == null)
				{
					_ShoppingCartItemService = new Service.ShoppingCartItemService();
				}

				if(_ProductService == null)
				{
					_ProductService = new Service.ProductService();
				}

				var userID = (Guid)user.ProviderUserKey;
				var currentLanguageID = SiteContext.Current.WorkingLanguage.LanguageId;

				var cartList = (from cart in _ShoppingCartItemService.GetShoppingCartItemByUser(userID)
								join prod in _ProductService.GetProductsByLanguage(currentLanguageID) on cart.ProductID equals prod.ProductID
								select new
								{
									ProductID = prod.ProductID,
									ProductName = prod.Name,
									ListPrice = prod.ListPrice,
									Quantity = cart.Quantity,
									ShoppingCartItemID = cart.ShoppingCartItemID
								});

				if (cartList != null && cartList.Count() > 0)
				{
					//var lstCartItems = cartList.ToList();

					GridOrderProduct.DataSource = cartList;
					GridOrderProduct.DataBind();

					var sumPrice = cartList.Sum(e => e.ListPrice * e.Quantity);

					LiteralOrderSummaryPrice.Text = sumPrice.Value.ToString("c2");
				}
			}
		}
	}
}